<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2011 Grzegorz Bańka <grzegorz@grzegorzbanka.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */


$LANG->includeLLFile('EXT:mtgenerator_news/mod1/locallang.xml');
require_once(PATH_t3lib . 'class.t3lib_scbase.php');
require_once (PATH_t3lib.'class.t3lib_pagetree.php');
require_once(t3lib_extMgm::extPath('tt_news').'lib/class.tx_ttnews_categorytree.php');

$BE_USER->modAccess($MCONF,1);	// This checks permissions and exits if the users has no permission for entry.
	// DEFAULT initialization of a module [END]



/**
 * Module 'MT generator tt_news ' for the 'mtgenerator_news' extension.
 *
 * @author	Grzegorz Bańka <grzegorz@grzegorzbanka.com>
 * @package	TYPO3
 * @subpackage	tx_mtgeneratornews
 */
class  tx_mtgeneratornews_module1 extends t3lib_SCbase {
				var $pageinfo;

				/**
				 * Initializes the Module
				 * @return	void
				 */
				function init()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					parent::init();

					/*
					if (t3lib_div::_GP('clear_all_cache'))	{
						$this->include_once[] = PATH_t3lib.'class.t3lib_tcemain.php';
					}
					*/
				}

				/**
				 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
				 *
				 * @return	void
				 */
				function menuConfig()	{
					global $LANG;
					$this->MOD_MENU = Array (
						'function' => Array (
							'1' => $LANG->getLL('function1')
						)
					);
					parent::menuConfig();
				}

				/**
				 * Main function of the module. Write the content to $this->content
				 * If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
				 *
				 * @return	[type]		...
				 */
				function main()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					// Access check!
					// The page will show only if there is a valid page and if this page may be viewed by the user
					$this->pageinfo = t3lib_BEfunc::readPageAccess($this->id,$this->perms_clause);
					$access = is_array($this->pageinfo) ? 1 : 0;
				
					if (($this->id && $access) || ($BE_USER->user['admin'] && !$this->id))	{

							// Draw the header.
						$this->doc = t3lib_div::makeInstance('mediumDoc');
						
						$this->doc->backPath = $BACK_PATH;
						$this->doc->form='<form action="" method="post" enctype="multipart/form-data">';

$this->doc->inDocStyles .= '
.installweb {
padding:10px;
}
div.typo3-mediumDoc {
width:100%;
}
.mt_gen_all {
padding:10px;
position:relative;
}
.mt_gen_all ol {
list-style:decimal;
}
.mt_gen_all ul {
padding:5px;
margin:5px;
}
.mt_gen_all table#typo3-tree {
padding:0;
margin:0;
}
body ul {
padding-left:10px;
list-style:disc;
margin:0 5px;
}
body ul li {
padding:3px;
}
.mtcatmenu {
display:none;
position:absolute;
top:100px;
width:500px;
left:25%;
background:#999999;
}
#mtgen_ligthbox {
display:none;
}
';							// JavaScript
						$this->doc->JScode = '
							<script language="javascript" type="text/javascript">
								script_ended = 0;
								function jumpToUrl(URL)	{
									document.location = URL;
								}
								var selected_tree=new Array();
								var new_selected_tree= new Array();
								function jumpTo(id,what,row,use)
								{
									if(id!=0)
									{
										new_selected_tree= new Array();
										if(inArray(id,selected_tree)) 
										{
											
											document.getElementById(\'row\'+id+\'_0\').style.background=\'none\';
											for(i=0; i<selected_tree.length; i++)
											{
												if(selected_tree[i]!=id) new_selected_tree[new_selected_tree.length]=id;
											}
											selected_tree=new_selected_tree;
										}
										else 
										{
											document.getElementById(\'row\'+id+\'_0\').style.background=\'green\';
											selected_tree[selected_tree.length]=id;
										}
									}
									return false;
								}
								function inArray(needle, haystack) {
								
									var length = haystack.length;
									for(var i = 0; i < length; i++) {
										if(haystack[i] == needle) return true;
									}
									return false;
								}
								function mtgen_confirm()
								{
									//mtgen_uid			
									document.getElementById(\'mtgen_uid\').value=selected_tree.join(",");	
								}
								function mtgen_addcat(id)
								{
									var name=\'mtgenmenucat\';
									//document.getElementById(name).style.display=\'block\';
									var value=document.getElementById(name).innerHTML;
									//alert(value.replace(/###CATUID###/g,id));
									document.getElementById(\'mtgen_ligthbox\').innerHTML=value.replace(/###CATUID###/g,id);
									
									document.getElementById(\'mt_gen_all\').style.display=\'none\';
									document.getElementById(\'mtgen_ligthbox\').style.display=\'block\';
									
								}
								function  addCat(cat,id)
								{
									//alert(cat);
									var isadd = document.getElementById(\'mtgen_pages_cat_\'+id).value;
									//alert(isadd.length);
									if(isadd.length==0) 
									{
										document.getElementById(\'mtgen_pages_cat_\'+id).value=cat;
									}else 
									{
										if(document.getElementById(\'mtgen_pages_cat_\'+id).value.charAt(document.getElementById(\'mtgen_pages_cat_\'+id).value.length-1)!=\'|\') document.getElementById(\'mtgen_pages_cat_\'+id).value=isadd+\',\'+cat;
										else document.getElementById(\'mtgen_pages_cat_\'+id).value=isadd+cat;
									}
									document.getElementById(\'mt_gen_all\').style.display=\'block\';
									document.getElementById(\'mtgen_ligthbox\').style.display=\'none\';
								}
								function mtgen_addsep(id)
								{
									var isadd = document.getElementById(\'mtgen_pages_cat_\'+id).value;
									//alert(isadd.length);
									if(isadd.length==0) 
									{
										alert(\'Musisz dodać minimum jedną kategorie\');
									}else 
									{
										document.getElementById(\'mtgen_pages_cat_\'+id).value=isadd+\'|\';
										alert(\'Dodaje separator\');
									}	
									
								}

								
							</script>
							
							
						';
						$this->doc->postCode='
							<script language="javascript" type="text/javascript">
								script_ended = 1;
								if (top.fsMod) top.fsMod.recentIds["web"] = 0;
							</script>
						';

						$headerSection = $this->doc->getHeader('pages', $this->pageinfo, $this->pageinfo['_thePath']) . '<br />'
							. $LANG->sL('LLL:EXT:lang/locallang_core.xml:labels.path') . ': ' . t3lib_div::fixed_lgd_cs($this->pageinfo['_thePath'], -50);

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->section('',$this->doc->funcMenu($headerSection,t3lib_BEfunc::getFuncMenu($this->id,'SET[function]',$this->MOD_SETTINGS['function'],$this->MOD_MENU['function'])));
						$this->content.=$this->doc->divider(5);


						// Render content:
						$this->moduleContent();


						// ShortCut
						if ($BE_USER->mayMakeShortcut())	{
							$this->content.=$this->doc->spacer(20).$this->doc->section('',$this->doc->makeShortcutIcon('id',implode(',',array_keys($this->MOD_MENU)),$this->MCONF['name']));
						}

						$this->content.=$this->doc->spacer(10);
					} else {
							// If no access or if ID == zero

						$this->doc = t3lib_div::makeInstance('mediumDoc');
						$this->doc->backPath = $BACK_PATH;

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->spacer(10);
					}
				
				}

				/**
				 * Prints out the module HTML
				 *
				 * @return	void
				 */
				function printContent()	{

					$this->content.=$this->doc->endPage();
					echo $this->content;
				}

				function check_rootpage($uid)
				{
					$error=1;
				
					$where = 'deleted=0 AND hidden=0 AND is_siteroot=0 AND uid='.$uid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','pages',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$error=0;
						$title_website=$row['title'];
					}	
					if($error==0)
					{
						$error=1;
						$where = 'deleted=0 AND hidden=0 AND is_siteroot=1 AND pid='.$uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,storage_pid','pages',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$storagefolder=$row['storage_pid'];
							$rootsite=$row['uid'];							
							if($storage_pid!=0 || $rootsite!=0) $error=0;
							else $error=1;
						}	
					}
					return array($title_website,$rootsite,$storagefolder,$error);			
				}
				 
				/**
				 * Generates the module content
				 *
				 * @return	void
				 */
				function moduleContent()	{
					switch((string)$this->MOD_SETTINGS['function'])	{
						case 1:
							if(isset($_GET['id']) && !isset($_POST['mtgen_rootpage']))
							{
								$_POST['mtgen_rootpage']=intval($_GET['id']);
							}
							if(isset($_POST['mtgen_gen_and_leave']))		$content=$this->generate(0);
							elseif(isset($_POST['mtgen_gen_and_delete']))	$content=$this->generate(1);
							elseif(isset($_POST['mtgen_allgen']))			$content=$this->check_select_page();
							elseif(isset($_POST['mtgen_rootpage']))
							{
								list($title_website,$rootsite,$storagefolder,$error)=$this->check_rootpage(intval($_POST['mtgen_rootpage']));
								
								if($error==0)
								{
									$path=$_SERVER['DOCUMENT_ROOT'];
									if($path!='/') $path=$path.'/';	
									$file_url=$path.'fileadmin/user/example_images';		
									
									$get_pagetree=$this->get_pagetree($rootsite,9);					
				
									$content='
									<input name="mtgen_rootpage" type="hidden" value="'.intval($_POST['mtgen_rootpage']).'" />
									<input name="mtgen_uid" id="mtgen_uid" type="hidden" value="" />
									<input name="mtgen_storagefolder" type="hidden" value="'.$storagefolder.'" />
									
									
									<div align="center"><strong>Generowanie tt_news jako przykładowe teksty na strone</strong></div><br />
									
									Wybrałeś stronę: <b>'.$title_website.'</b>, wybierz {super_uid} na jakich podstronach chcesz umieścić przykładowe treści (tt_news) - opcje <b>rekursywne pobieranie stron</b> możesz użyć poniżej tego drzewa strony<br />
									'.$this->get_printTree($get_pagetree).'
									
									Możesz użyć działania rekursywnego (czytanie LVL wybranej strony/stron w dół) standardowo 0 a maksymalnie 4 lvl, to będzie działać na wszystkie wybrane podstrony {super_uid}.
									
									<select name="mtgen_reclvl">
									  <option value="0">None recursiv</option>
									  <option value="1">LVL 1</option>
									  <option value="2">LVL 2</option>
									  <option value="3">LVL 3</option>
									  <option value="4">LVL 4</option>
									</select>
									
									<p>Jeśli użyłeś działania rekursywnego (większego niż standardowe 0 LVL) i chcesz aby główny/główne {super_uid} nie były brane pod uwagę podczas dodawania przykładowej treści, zaznacz tą opcje: <input name="mtgen_recisempty" type="checkbox" value="1" /</p>
									<br /><hr>
									
									Jak dużo przykładowych tt_news (treści) ma zostać dodanych dla jednej strony (page uid)? <input name="mtgen_count_news" type="text" value="'.rand(5,22).'" /> (max 99) <br /><hr>
									Lub jeśli chcesz aby na każdej ze stron była losowa ilość zaznacz tą opcje: <input name="mtgen_count_random" type="checkbox" value="1" /> 
									i podaj od ilu liczyć random: <input name="mtgen_count_rand_0" type="text" value="0" /> i jaki ma być maksymalny random <input name="mtgen_count_rand_1" type="text" value="10" /> (max 99)<br /><hr>
									
									Użyj ścieżki do przykładowych zdjęć (images): <input name="mtgen_exampleimg" type="text" /> standardowo jest to ścieżka /fileadmin/mtexampleimages , jeśli chcesz użyć standardowej ścieżki nie wypełniaj tego pola<br /><hr>
									<p>tutaj możesz dodać więcej przykładowych zdjęć-> <b><a href="/typo3/sysext/filelist/mod1/file_list.php?id='.$file_url.'">upload example images</a></b></p>
									<hr><br />
									Jeśli wszystko ustawiłeś i jesteś gotowy generować przykładowe treści to kliknij tutaj: 
									<input name="mtgen_allgen" type="submit" value="Generate all" onClick="mtgen_confirm(); return confirm(\'Are you sure that you want use this?\')" />
	
									';
								}else $content='
								<b>Błąd, prawdopodobnie wybrałeś złą stornę</b>
								<h3>Wybierz stronę na której chcesz dodać treści</h3>
								<p>Użyj drzewa stron po lewej stronie i kliknij na nazwę strony (skrót) a nie na (stronę główną / rootpage)</p>
								';
							}else 
							{
								$content='
								<h3>Wybierz stronę na której chcesz dodać treści</h3>
								<p>Użyj drzewa stron po lewej stronie i kliknij na nazwę strony (skrót) a nie na (stronę główną / rootpage)</p>
								';
							}
							$this->content.=$this->doc->section('Generator:',$content,0,1);
						break;
					}
				}
				function generate($option)
				{
					switch($option)
					{
						case '0':
							$return='<b>Dodano tt_news, zostawiono stare</b>';
							$this->add_new_news();
						break;
						case '1':
							$return='<b>Dodano tt_news, stare zostały usunięte</b>';
							$this->delete_all_news();
							$this->add_new_news();							
						break;
						case '2':
							$return='2a';
						break;
						case '3':
							$return='<b>ERROR, ten folder nie posiada w sobie newsów</b>';
							
						break;
					}
					//print_r($_POST);
					return $return;
				}
				function delete_all_news()
				{
					$mtgen_pages_cat=$_POST['mtgen_pages_cat'];
					$pages=array_keys($mtgen_pages_cat);
					for($i=0; $i<count($pages); $i++)
					{
						$pid=$pages[$i];
						$where = 'deleted=0 AND hidden=0 AND pid='.$pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_news',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$this->delete_all_with_news($row['uid']);							
						}
					}
				}
				function delete_all_with_news($uid)
				{
					$update=array(
						'deleted'	=>	1
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_news','uid='.$uid,$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);

					$query = $GLOBALS['TYPO3_DB']->DELETEquery('tt_news_cat_mm', 'uid_local="'.$uid.'"');		
					$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);	
					
					$query = $GLOBALS['TYPO3_DB']->DELETEquery('tt_news_related_mm', 'uid_local="'.$uid.'"');		
					$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
				function add_new_news()
				{
					//print_r($_POST);
					$return_uid=array();
					
					$mtgen_count_news=intval($_POST['mtgen_count_news']);
					$mtgen_count_random=intval($_POST['mtgen_count_random']);
					$mtgen_count_rand_0=intval($_POST['mtgen_count_rand_0']);
					$mtgen_count_rand_1=intval($_POST['mtgen_count_rand_1']);
					$mtgen_reclvl=intval($_POST['mtgen_reclvl']);
					$mtgen_pages_cat=$_POST['mtgen_pages_cat'];
					
					$mtgen_page_news=addslashes($_POST['mtgen_page_news']);
					if(stristr($mtgen_page_news,',')) $mtgen_page_news=explode(',',$mtgen_page_news);
					else $mtgen_page_news=array($mtgen_page_news);
					
					$mtgen_exampleimg=$_POST['mtgen_exampleimg']?'':'/fileadmin/mtexampleimages';;
					
					$loc_path=$_SERVER['DOCUMENT_ROOT'];
					if($loc_path!='/') $loc_path=$loc_path.'/';
					if(is_dir($loc_path.$mtgen_exampleimg)) $mtgen_exampleimg=str_replace('//','/',$loc_path.$mtgen_exampleimg);
					else $mtgen_exampleimg=str_replace('//','/',$loc_path.'/fileadmin/mtexampleimages');
					
					$pages=array_keys($mtgen_pages_cat);
					//print_r($pages_cat);
					
					if($mtgen_count_random==0)
					{
						//$this->insert_news($mtgen_count_news,$mtgen_exampleimg);
						if($mtgen_count_news>99) $mtgen_count_news=99;
						for($i=0; $i<count($pages); $i++)
						{
							$pages_uid=$pages[$i];
							$cat_value=$mtgen_pages_cat[$pages_uid];
							if(stristr($cat_value,'|')) $cat_value=explode('|',$cat_value);
							else $cat_value=array($cat_value);							
							$pages_cat=$cat_value;
							$return_uid=array_merge($return_uid,$this->insert_news($mtgen_count_news,$mtgen_exampleimg,$pages_uid,$pages_cat));				
						}						
					}
					$this->tt_news_related_mm($return_uid);
				}
				function tt_news_related_mm($uids)
				{
					for($i=0; $i<count($uids); $i++)
					{
						$uid=$uids[$i];
						$rand=rand(0,5);
						if($rand==5)
						{
							for($z=0; $z<rand(1,8); $z++)
							{
								//tt_news_related_mm
								$query=array(
								'uid_local'		=>	$uid,
								'uid_foreign'	=>	$uids[rand(0,count($uids)-1)],
								'sorting'		=>	$i,
								'tablenames'	=>	'tt_news'
								);
								
								$GLOBALS['TYPO3_DB']->exec_INSERTquery(
										'tt_news_related_mm',
										$query
								);
								
							}
						}
					}
				}
				function insert_news($mtgen_count_news,$mtgen_exampleimg,$pages_uid,$pages_cat)
				{
					//print_r($mtgen_exampleimg);
					$return_uid=array();
					$path_img=$mtgen_exampleimg;
					$mtgen_exampleimg=$this->get_mtgen_exampleimg($mtgen_exampleimg);
				
					for($i=0; $i<$mtgen_count_news; $i++)
					{
					
					
						$text_example=$this->text_example();
						$title=$this->title_example();
						$get_pages_cat=$pages_cat[rand(0,count($pages_cat)-1)];
						$time=$this->gen_time();
						
						$query=array(
							'pid'	=>	$pages_uid,
							'tstamp'	=>	$time,
							'crdate'	=>	$time,
							'title'		=>	$title,
							'bodytext'	=>	$text_example,
							'datetime'	=>	$time,
							'image'		=>	$this->add_image($mtgen_exampleimg,$path_img),
							'keywords'	=>	$this->get_keywords()
						);
						
						$GLOBALS['TYPO3_DB']->exec_INSERTquery(
								'tt_news',
								$query
						);
						$uid_news=$GLOBALS['TYPO3_DB']->sql_insert_id();
						$this->add_cat($pages_cat,$uid_news);
						$return_uid[]=$uid_news;
						
					}
					return $return_uid;
						
				}	
				function gen_time($time=0,$next='')
				{
					if($time==0) $time=time();
					if($next=='') return $time - (rand(2,99) * rand(0,24) * rand(0,60) * rand(0,60));
					else return $time + (rand(2,99) * rand(0,24) * rand(0,60) * rand(0,60));
				}
				function get_keywords()
				{
					$keys='Lorem ipsum dolor sit amet, consectetur adipiscing elit Maecenas a ligula enim Donec lectus metus, tincidunt sit amet blandit ut, tincidunt ut augue Donec porttitor egestas turpis ut tempus Nulla facilisi Ut nec risus id tellus imperdiet feugiat ut et nulla Curabitur pellentesque nisl ac eros facilisis non vulputate enim auctor Proin dapibus tristique libero non bibendum';
					$arr=explode(' ',$keys);
					$rand=rand(3,20);
					for($i=0; $i<$rand; $i++)
					{
						$add[]=$arr[rand(0,count($arr)-1)];
					}
					return implode(', ',$add);
				}
				function add_cat($cat,$news)
				{
					$count=0;
					$iscat=$cat[rand(0,count($cat)-1)];
					if($iscat!='')
					{
						if(stristr($iscat,',')) $iscat=explode(',',$iscat);
						else $iscat=array($iscat);
						$iscat=array_unique($iscat);
						$iscat=array_values($iscat);
						
						for($i=0; $i<count($iscat); $i++)
						{
							$query=array(
								'uid_local'		=>	$news,
								'uid_foreign'	=>	$iscat[$i],
								'sorting'		=>	$i+1
							);
							
							$GLOBALS['TYPO3_DB']->exec_INSERTquery(
									'tt_news_cat_mm',
									$query
							);
							$count=$i;
						}
					}
					//return $count;
					
				}	
				function add_image($img,$path)
				{
					$return=array();
					$loc_path=$_SERVER['DOCUMENT_ROOT'];
					if($loc_path!='/') $loc_path=$loc_path.'/';
					
					$rand_img=rand(1,4);
					for($i=0; $i<$rand_img; $i++)
					{
						$addimg='';
						$rand=rand(0,count($img)-1);						
						$addimg=$img[$rand];						
						if($addimg!='')
						{
							
							if(!is_file($loc_path.'uploads/pics/'.$addimg))
							{
								//print_r($loc_path.'uploads/pics/'.$img);
								system('cp '.$path.'/'.$addimg.' '.$loc_path.'uploads/pics/');
							}
							$return[]=$addimg;
						}
					}
					//if(intval($addimg)!=0) $addimg='';
					return implode(',',$return);
				}	
				function get_mtgen_exampleimg($path)
				{
					$img=array();
					if(is_dir($path))
					{
						$get=t3lib_div::getFilesInDir($path,'jpg');
						if(count($get)!=0) $img=array_values($get);
					}
					return $img;
				}
				function check_select_page()
				{
					global $LANG;
					
					$mtgen_count_news=intval($_POST['mtgen_count_news']);
					$mtgen_count_random=intval($_POST['mtgen_count_random']);
					$mtgen_count_rand_0=intval($_POST['mtgen_count_rand_0']);
					$mtgen_count_rand_1=intval($_POST['mtgen_count_rand_1']);
					$mtgen_reclvl=intval($_POST['mtgen_reclvl']);
					$mtgen_recisempty=intval($_POST['mtgen_recisempty']);
					$mtgen_exampleimg=$_POST['mtgen_exampleimg'];
					$mtgen_storagefolder=intval($_POST['mtgen_storagefolder']);
					
					$loc_path=$_SERVER['DOCUMENT_ROOT'];
					if($loc_path!='/') $loc_path=$loc_path.'/';
					if(is_dir($loc_path.$mtgen_exampleimg)) $mtgen_exampleimg=$mtgen_exampleimg;
					else $mtgen_exampleimg='/fileadmin/mtexampleimages';
					
					$mtgen_uid=$_POST['mtgen_uid'];
					if(stristr($mtgen_uid,',')) $mtgen_uid=explode(',',$mtgen_uid);
					else $mtgen_uid=array($mtgen_uid);
					$all_mtgen_uid=$mtgen_uid;
					
					$rec=intval($_POST['mtgen_reclvl']);
					$rec=0?1:$rec;
					if($rec>4)$rec=4;
					
					$is_news=0;
					$where_news=array();
					$send_uid=array();
					$return_norec=array();
					
					$mtgen_uid=array_unique($mtgen_uid);
					
					for($i=0; $i<count($mtgen_uid); $i++)
					{
						
						$uid=intval($mtgen_uid[$i]);
						$send_uid[]=$uid;
						$mtgen_uid[$i]=$uid;
						
						$where = 'deleted=0 AND hidden=0 AND pid='.$uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tt_news',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$is_news=1;
							$where_news[$row['uid']]=$row['title'];						
						}
						if($rec!=0)
						{
							$return_norec=0;
							$get_rec=$this->get_pagetree($uid,$rec);					
							for($z=0; $z<count($get_rec); $z++)
							{
								$rec_uid = $get_rec[$z]['row']['uid'];
								$send_uid[]=$rec_uid;
								if(!in_array($rec_uid,$send_uid))
								{
									if($is_news==0) list($is_news,$add_where_news) = $this->check_rec_news($rec_uid);
									$where_news=array_merge($where_news,$add_where_news);
								}
							}							
						}else
						{
							$return_norec=0;
							$where = 'deleted=0 AND hidden=0 AND uid='.$uid;
							$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','pages',$where);
							while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
							{
								//$return_norec[]='<ol>'.$row['title'].'{'.$row['uid'].'}</ol>';	
								$add_hide_uid[]=$row['uid'];
								$all_mtgen_uid[]=$row['uid'];			
							}
						}
					}
					if($is_news==1 || 1==1)
					{
						
						if($return_norec==0) 
						{
							list($selected_tree,$add_hide_uid)=$this->get_selected_tree($all_mtgen_uid,$mtgen_recisempty,$rec,$mtgen_recisempty,$mtgen_storagefolder);
							$return_norec='';
						}else $return_norec='<ul>'.implode("\n",$return_norec).'</ul>';
						$this->get_ttnews_catree(10,9);
						return '
							<div class="mt_gen_all" id="mt_gen_all">
								Znaleziono na stronie/stronach tt_news w ilości: <b>['.count($where_news).']</b><br /><hr>
								<h2>Dodajesz newsy do:</h2>
								'.$return_norec.'
								'.$selected_tree.'
								
								<ul>
									<ol>Add new news and leave old news <input name="mtgen_gen_and_leave" type="submit" value="Add news and leave old news" onClick="return confirm(\'Are you sure - you leave old news\')" /></ol>
									<ol>Add new news and delete old news <input name="mtgen_gen_and_delete" type="submit" value="Add new news and remove all old news" onClick="return confirm(\'Are you sure - you DELETE old news\')"/></ol>
								</ul>
								
									<input name="mtgen_count_news" type="hidden" value="'.$mtgen_count_news.'" />
									<input name="mtgen_count_random" type="hidden" value="'.$mtgen_count_random.'" />
									<input name="mtgen_count_rand_0" type="hidden" value="'.$mtgen_count_rand_0.'" />
									<input name="mtgen_count_rand_1" type="hidden" value="'.$mtgen_count_rand_1.'" />
									<input name="mtgen_reclvl" type="hidden" value="'.$mtgen_reclvl.'" />
									<input name="mtgen_page_news" type="hidden" value="'.implode(',',$add_hide_uid).'" />
									<input name="mtgen_exampleimg" type="hidden" value="'.$mtgen_exampleimg.'" />
							</div>
							<div class="mtgen_ligthbox" id="mtgen_ligthbox">
							
							</div>
						';
					}else
					{
						return $this->generate(3);
					}
				}
				function check_if_pid($uid,$pid)
				{
					$return=1;
					$where = 'deleted=0 AND hidden=0 AND uid='.$uid.' AND pid ='.$pid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','pages',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$return=0;
					}	
					return $return;
				}
				function hide_select_pages($pages)
				{
					for($i=0; $i<count($pages); $i++)
					{
						$update=array(
							'deleted'	=>	1
						);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$pages[$i],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					}
				}
				function unhide_select_page($uid)
				{
					$update=array(
						'deleted'	=>	0
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$uid,$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);	
				}
				function generate_catmenu($pid,$subcat='')
				{
					if($subcat=='') $parent_category=0;
					else $parent_category=$subcat;
					
					$where = 'deleted=0 AND hidden=0 AND pid='.$pid.' AND parent_category='.$parent_category;
					//print_r($where);
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tt_news_cat',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$add[]=array($row['title'],$row['uid'],$this->generate_catmenu($pid,$row['uid']));
					}
					return $add;
				}
				function render_catmenu($add)
				{
						$name=$add[0];
						$id=$add[1];
						$subcat=$add[2];
						if(is_array($subcat)) 
						{
							$add_subcat=array();
							for($i=0; $i<count($subcat); $i++)
							{
								$add_subcat[]=$this->render_catmenu($subcat[$i]);
							}
							//print_r($add_subcat);exit;
							$add_subcat=implode("\n",$add_subcat);
						}
						else $subcat='';
						
						$return[]='<ul><li><a href="#" onClick="addCat(\''.$id.'\',\'###CATUID###\')" id="mtgen_cat'.$id.'" >'.$name.'</a>'.$add_subcat."</li></ul>\n";
						return implode("|",$return);
					
				}
				function get_selected_tree($all_mtgen_uid,$mtgen_recisempty,$rec,$mtgen_recisempty,$mtgen_storagefolder)
				{
					$iscat = $this->generate_catmenu($mtgen_storagefolder);
					for($i=0; $i<count($iscat); $i++)
					{
						$add_cat[]=$this->render_catmenu($iscat[$i]);
					}		
					$add_cat='<div class="mtcatmenu" id="mtgenmenucat">'.implode("\n",$add_cat).'</div>';			
					
					$help_info='<a href="#" onClick="alert(\'Jakie kategorie mają być dodane, oddziel przecinkami jeśli ma być dodane klika jeśli mają być dodane randomowo oddziel je pionową kreską przykłądy: 2,4,5 lub np: 3,4|3|4|2,4,5|1\')">pomoc</a>';
					$this->hide_select_pages($all_mtgen_uid);
					
					$invertedDepth=$uid_pid=$is_add=array();
					for($i=0; $i<count($all_mtgen_uid); $i++)
					{
						$uid=$all_mtgen_uid[$i];
						$this->unhide_select_page($uid);
						
						$where = 'deleted=0 AND hidden=0 AND uid='.$uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','pages',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							if($rec!=0)
							{
								$add_first[]=$row;
								$title[$uid]=$row['title'];
								$get_all=$this->get_pagetree($uid,$rec);
								$add[$uid]=$get_all;
							}else
							{
								$add_first[]=$row;
								$title[$uid]=$row['title'];
								$add[$uid]=array();
							}
						}
					}

					$key=array_keys($add);
					for($i=0; $i<count($key); $i++)
					{
						$uid=$key[$i];
						$add_replace_title=$add_replace_title_to=array();
						
						if($mtgen_recisempty==1) $add_title='(w tej stronie nie zostaną dodane tt_news)';
						else $add_title='
							<input name="mtgen_pages_cat['.$uid.']" type="text" id="mtgen_pages_cat_'.$uid.'" value="" /> 
							
							'.$help_info.'
							- <a href="#" onClick="mtgen_addcat(\''.$uid.'\')">dodaj kategorie</a>		
							- <a href="#" onClick="mtgen_addsep(\''.$uid.'\')">dodaj random</a>					
							';
							
						if($add_title=='') $add_hide_uid[]=$uid;
						if(!in_array($uid,$is_add) || count($all_mtgen_uid)==1) 
						{							
							for($z=0; $z<count($add[$uid]); $z++)
							{
								if(!in_array($add[$uid][$z]['row']['uid'],$all_mtgen_uid))
								{
									$add_hide_uid[]=$add[$uid][$z]['row']['uid'];
								}
							}
							$get_tree=$this->get_printTree($add[$uid]);
							for($z=0; $z<count($add[$uid]); $z++)
							{
								$replace=$add[$uid][$z]['row']['title'].'</a>';
								$replace_to=$replace.'
								<input name="mtgen_pages_cat['.$add[$uid][$z]['row']['uid'].']" type="text" id="mtgen_pages_cat_'.$add[$uid][$z]['row']['uid'].'" value="" /> 
								
								'.$help_info.'
								- <a href="#" onClick="mtgen_addcat(\''.$add[$uid][$z]['row']['uid'].'\')">dodaj kategorie</a>	
								- <a href="#" onClick="mtgen_addsep(\''.$add[$uid][$z]['row']['uid'].'\')">dodaj random</a>
								';
								$get_tree=str_replace($replace,$replace_to,$get_tree);
							}
							$add_tree[]='<h3>'.$title[$uid].' {'.$uid.'} '.$add_title.'</h3>
							'.$get_tree;
						}
					}

					return array(implode("\n",$add_tree).$add_cat,$add_hide_uid);

				}
				function check_rec_news($uid)
				{
					$where_news=array();
					$is_news=0;
					$where = 'deleted=0 AND hidden=0 AND pid='.$uid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tt_news',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$is_news=1;
						$where_news[$row['uid']]=$row['title'];
					}
					return array($is_news,$where_news);
				}
				function get_ttnews_catree($uid,$dep)
				{
					$tree = new tx_ttnews_categorytree;
					$tree = $tree->getTree($uid, $dep);
					print_r($tree);
				}
				function get_printTree($alltree)
				{
					$tree = t3lib_div::makeInstance('t3lib_pageTree');
					$tree->init('AND '.$GLOBALS['BE_USER']->getPagePermsClause(1));
					return $tree->printTree($alltree);
				}
				function get_pagetree($uid,$rec,$pid='')
				{
					if($pid!='')
					{
						if(stristr($pid,',')) $pid=explode(',',$pid);
						else $pid=array();
					}
					
					$tree = t3lib_div::makeInstance('t3lib_pageTree');
					$tree->init('AND '.$GLOBALS['BE_USER']->getPagePermsClause(1).' AND hidden=0'.$pid);
					//print_r($tree->getRecord('7'));exit;
					$cos = $tree->getTree($uid, $rec, '');
					$alltree=$tree->tree;
					return $alltree;
				}
				function text_example()
				{
					$rand=rand(35,165);
					$text='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas a ligula enim. Donec lectus metus, tincidunt sit amet blandit ut, tincidunt ut augue. Donec porttitor egestas turpis ut tempus. Nulla facilisi. Ut nec risus id tellus imperdiet feugiat ut et nulla. Curabitur pellentesque nisl ac eros facilisis non vulputate enim auctor. Proin dapibus tristique libero non bibendum.In mi velit, aliquet eu scelerisque faucibus, semper id arcu. Nunc vel metus odio. Nulla pellentesque viverra nisl ac ornare. Maecenas ac velit nunc. Duis pharetra, erat sit amet ornare rutrum, mi dolor tempor nulla, ut posuere metus lectus eget erat. Fusce facilisis turpis sit amet mauris interdum in suscipit mauris commodo. Nam consectetur enim ac odio molestie a pulvinar dui pulvinar. Praesent eu massa eget quam placerat ultrices id ut ante. Duis faucibus porttitor mi, sit amet lobortis urna iaculis nec. Donec viverra consequat sem, eget consectetur odio aliquam id. Mauris in dui ac lacus tincidunt vehicula. Etiam nec tortor dolor, sed vehicula turpis. Nunc sit amet ante sit amet eros molestie condimentum nec vel nisi. Vestibulum sed turpis ante.Suspendisse sed vestibulum augue. Nullam vulputate, lacus non dictum interdum, enim lacus rhoncus arcu, non consectetur neque enim sed lectus. Curabitur porttitor lectus at lorem vulputate fermentum. Fusce viverra, nisi a eleifend ullamcorper, dolor tellus tristique odio, eu posuere dui nibh eget erat. Vivamus nibh magna, fermentum ut commodo a, dictum consectetur leo. Praesent placerat varius leo, in egestas neque bibendum rhoncus. Fusce sit amet arcu tortor. Nunc sodales tincidunt euismod. Integer hendrerit erat et nulla posuere ut aliquet neque tempus. Proin eleifend ipsum tortor. Quisque eget sem turpis. Vivamus gravida quam sit amet arcu consequat sit amet condimentum velit tincidunt.Phasellus arcu quam, mattis vitae rhoncus a, egestas eget quam. Pellentesque nibh lectus, feugiat eu ullamcorper rhoncus, adipiscing commodo erat. Morbi pellentesque eleifend turpis id venenatis. Sed aliquet feugiat dui, in ullamcorper lectus hendrerit id. Pellentesque gravida leo sit amet arcu ultrices eleifend. Suspendisse dolor purus, laoreet posuere pharetra ac, elementum in arcu. Cras ac quam in elit elementum iaculis sit amet in massa. Nulla sed dapibus sapien.Aenean suscipit, erat vitae malesuada elementum, enim lacus fermentum mauris, eu pellentesque lectus magna quis libero. Nulla facilisi. Integer volutpat risus a felis lacinia vitae pharetra risus dignissim. Duis eu tellus risus. Nullam massa lacus, interdum pretium ullamcorper nec, feugiat nec odio. Aliquam erat volutpat. Phasellus egestas risus vitae risus imperdiet rhoncus. Pellentesque a tellus et lorem sodales mattis ac vel mauris. Etiam sodales porta venenatis. In sit amet elit mauris. Donec sed erat a turpis lacinia feugiat. Sed eget ipsum sed ligula euismod adipiscing.';
					$arr=explode('. ',$text);
					$sep=rand(0,15);
					for($i=0; $i<$rand; $i++)
					{
						if($sep==1) $add_par="\n";
						else $add_par='';
						$return[]=$add_par.$this->get_rext_rand($arr[rand(0,count($arr)-1)]);
						$sep=rand(0,15);	
					}
					return implode('. ',$return);
				}
				function get_rext_rand($text)
				{
					$text=explode(' ',$text);
					for($i=0; $i<count($text); $i++)
					{
						$rand=rand(0,145);
						if($rand==1) $return[$i]='<b>'.$text[$i].'</b>';
						elseif($rand==2) $return[$i]='<a href="#">'.$text[$i].'</a>';
						else $return[$i]=$text[$i];
					}
					return implode(' ',$return);
				}
				function title_example()
				{
					$title='Lorem ipsum dolor sit amet, consectetur adipiscing elit Maecenas a ligula enim Donec lectus metus, tincidunt sit amet blandit ut, tincidunt ut augue Donec porttitor egestas turpis ut tempus Nulla facilisi Ut nec risus id tellus imperdiet feugiat ut et nulla Curabitur pellentesque nisl ac eros facilisis non vulputate enim auctor Proin dapibus tristique libero non bibendum';
					$title=explode(' ',$title);
					$rand=rand(5,15);
					for($i=0; $i<$rand; $i++)
					{
						$return[]=$title[rand(0,count($title)-1)];
					}
					return ucfirst(strtolower(implode(' ',$return)));
				}
				
		}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtgenerator_news/mod1/index.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtgenerator_news/mod1/index.php']);
}




// Make instance:
$SOBE = t3lib_div::makeInstance('tx_mtgeneratornews_module1');
$SOBE->init();

// Include files?
foreach($SOBE->include_once as $INC_FILE)	include_once($INC_FILE);

$SOBE->main();
$SOBE->printContent();

?>